package org.qiyu.live.im.core.server.client.handler;

import com.alibaba.fastjson.JSON;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.qiyu.live.im.core.server.common.ImMsg;
import org.qiyu.live.im.core.server.common.ImMsgCodeEnum;
import org.qiyu.live.im.dto.ImMsgBody;

/**
 * Created with IntelliJ IDEA.
 * Description: 客户端的处理器
 * 1) 接收到消息之后要返回一个ack
 * User: sfx
 * Date: 2023-10-07
 * Time: 19:23
 */
public class ClientHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ImMsg imMsg = (ImMsg) msg;
        if(imMsg.getCode() == ImMsgCodeEnum.IM_BIZ_MSG.getCode()) {
            // 接受到服务端的消息之后(客户端A-->netty服务器-->客户端B),我们要回一个ack
            ImMsgBody respImMsgBody = JSON.parseObject(new String(imMsg.getBody()), ImMsgBody.class);
            ImMsgBody ackBody = new ImMsgBody();
            ackBody.setAppId(respImMsgBody.getAppId());
            ackBody.setMessageId(respImMsgBody.getMessageId());
            ackBody.setUserId(ackBody.getUserId());
            ImMsg ackImMsg = ImMsg.build(ImMsgCodeEnum.IM_ACK_MSG.getCode(), JSON.toJSONString(ackBody));
            // 客户端收到消息之后,给对方发送一个ack记录,代表他发送的消息,我这边接收到了
            ctx.writeAndFlush(ackImMsg);
        }
        System.out.println("【服务端响应数据】result is " + new String(imMsg.getBody()));
    }
}